<template>
  <div id="app">
    <input type="file" style="display:none;" id="file" />
    <el-button type="primary" @click="uploadFile">选择上传文件</el-button>
    <el-button type="warning" @click="confirmUpload">开始上传</el-button>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'App',
  data () {
    return {
      currentFile: null,
    }
  },
  methods: {

    // 点击上传按钮
    uploadFile () {
      const that = this;
      const fileNode = document.getElementById('file');
      fileNode.click();
      fileNode.addEventListener('change', function (ev) {
        that.currentFile = ev.target.files[0];
      })
    },
    // 上传前的钩子函数
    beforeUpload (file) {
      if (!file) {
        this.$message.warning('请选择上传的文件');
        return false;
      }
      const { type, size } = file;
      // 文件格式化校验
      if (!/(png|gif|jpeg|jpg)$/i.test(type)) {
        this.$message.warning("文件合适不正确");
        return false;
      }
      // 文件大小
      if (size > 5 * 1024 * 1024) {
        this.$message.warning('文件过大,请上传小于5MB的文件');
        return false;
      }
      return true;
    },
    // 开始上传
    async confirmUpload () {
      let formData = new FormData();
      const currentFile = this.currentFile;
      // 上传前的钩子函数
      const flag = this.beforeUpload(currentFile);
      if (!flag) {
        return false;
      };
      const result = await this.fileParse(currentFile, 'base64');
      const postData = {
        chunk: encodeURIComponent(result),
        filename: currentFile.name,
        title: '测试文件',
      };
      // 设置请求头
      const headers = {
        // "Content-Type": "multipart/form-data",
      }
      // 发送ajax请求
      axios.post('/upload2', postData, { headers }).then(res => {
        this.currentFile = null;
        console.log(res);
      })
    },
    // 将文件转换为bs64
    fileParse (file, type = "base64") {
      return new Promise(resolve => {
        let fileRead = new FileReader();
        if (type === "base64") {
          fileRead.readAsDataURL(file);
        } else if (type === "buffer") {
          fileRead.readAsArrayBuffer(file);
        }
        fileRead.onload = (ev) => {
          resolve(ev.target.result);
        };
      });
    }
  },
  components: {
  }
}
</script>

<style lang="less">
</style>
